'use strict';
const { Op } = require("sequelize");
const moment = require('moment');
const fs = require('fs');
const path = require('path');
const xlsx = require('xlsx');
const { v4: uuidv4 } = require('uuid');

/**
 * 获取软著列表
 */
async function getSoftwareCopyrightList(ctx) {
  let error = true;
  let rslt = null;
  let models = ctx.fs.dc.models;

  try {
    const { page = 1, pageSize = 10, keyword, sortField = 'id', sortOrder = 'asc', issueStartDate, issueEndDate } = ctx.request.query;
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    const whereCondition = {};
    
    // 关键字搜索 - 支持软件名称、登记号、著作权人字段
    if (keyword) {
      whereCondition[Op.or] = [
        { software_name: { [Op.like]: `%${keyword}%` } },
        { registration_number: { [Op.like]: `%${keyword}%` } },
        { copyright_holder: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    // 发证时间范围查询
    if (issueStartDate || issueEndDate) {
      whereCondition.issue_date = {};
      
      if (issueStartDate) {
        whereCondition.issue_date[Op.gte] = issueStartDate;
      }
      
      if (issueEndDate) {
        whereCondition.issue_date[Op.lte] = issueEndDate;
      }
    }
    
    // 查询总数
    const total = await models.SoftwareCopyright.count({
      where: whereCondition
    });
    
    // 排序方向
    let orderDirection = sortOrder.toUpperCase();
    // 将前端的ascend/descend转换为SQL需要的ASC/DESC
    if (orderDirection === 'ASCEND') {
      orderDirection = 'ASC';
    } else if (orderDirection === 'DESCEND') {
      orderDirection = 'DESC';
    }
    
    const order = [[sortField || 'id', orderDirection]];
    
    // 查询列表数据
    const data = await models.SoftwareCopyright.findAll({
      where: whereCondition,
      offset,
      limit,
      order
    });
    
    rslt = {
      data,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      total
    };
    error = false;
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "GetSoftwareCopyrightListError" };
  } else {
    ctx.status = 200;
    ctx.body = rslt;
  }
}

/**
 * 导入软著数据
 */
async function importSoftwareCopyright(ctx) {
  let error = true;
  let rslt = null;
  let models = ctx.fs.dc.models;

  try {
    // 检查是否有文件上传
    if (!ctx.request.files || !ctx.request.files.file) {
      ctx.status = 400;
      ctx.body = { error: "NoFileUploaded" };
      return;
    }

    const file = ctx.request.files.file;
    const filePath = file.path;
    
    // 读取Excel文件
    const workbook = xlsx.readFile(filePath);
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const data = xlsx.utils.sheet_to_json(worksheet);
    
    // 校验和导入数据
    const importResults = {
      success: 0,
      failed: 0,
      duplicates: [],
      errors: []
    };
    
    for (const row of data) {
      try {
        // 必要字段校验
        if (!row['软件名称'] || !row['登记号']) {
          importResults.failed++;
          importResults.errors.push(`行 ${importResults.success + importResults.failed}: 软件名称或登记号为空`);
          continue;
        }
        
        // 查询是否存在重复数据（软件名称+登记号）
        const existingRecord = await models.SoftwareCopyright.findOne({
          where: {
            software_name: row['软件名称'],
            registration_number: row['登记号']
          }
        });
        
        if (existingRecord) {
          importResults.failed++;
          importResults.duplicates.push(row['软件名称']);
          continue;
        }
        
        // 数据格式转换
        const softwareCopyrightData = {
          software_name: row['软件名称'],
          registration_number: row['登记号'],
          case_number: row['我司案号'] || null,
          inventors: row['发明人'] || null,
          disclosure_time: row['技术交底书收集时间'] ? moment(row['技术交底书收集时间']).format('YYYY-MM-DD') : null,
          development_complete_date: row['开发完成日期'] ? moment(row['开发完成日期']).format('YYYY-MM-DD') : null,
          acceptance_date: row['受理时间'] ? moment(row['受理时间']).format('YYYY-MM-DD') : null,
          issue_date: row['发证时间'] ? moment(row['发证时间']).format('YYYY-MM-DD') : null,
          related_product: row['关联产品'] || null,
          related_project: row['关联立项/课题'] || null,
          type: row['防御型/攻击型'] || null,
          first_publication_date: row['首次发表日期'] ? moment(row['首次发表日期']).format('YYYY-MM-DD') : null,
          copyright_holder: row['著作权人'] || null,
          status: row['状态'] || null,
          is_core: row['是否为核心'] === '是' ? true : false,
          core_score: row['核心分数'] || null,
          source_department: row['来源部门'] || null,
          agent_responsible: row['代理负责人'] || null,
          original_name: row['原名称'] || null,
          special_notes: row['特殊事项备注'] || null,
          dev_related_project: row['关联课题/项目'] || null
        };
        
        // 创建记录
        await models.SoftwareCopyright.create(softwareCopyrightData);
        importResults.success++;
      } catch (e) {
        importResults.failed++;
        importResults.errors.push(`行 ${importResults.success + importResults.failed}: ${e.message}`);
      }
    }
    
    // 删除临时文件
    fs.unlinkSync(filePath);
    
    rslt = {
      ...importResults,
      duplicateMessage: importResults.duplicates.length > 0 
        ? `${importResults.duplicates.join('、')} 已存在，请确认后重新导入` 
        : null
    };
    error = false;
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "ImportSoftwareCopyrightError" };
  } else {
    ctx.status = 200;
    ctx.body = rslt;
  }
}

/**
 * 创建软著
 */
async function createSoftwareCopyright(ctx) {
  let error = true;
  let rslt = null;
  let models = ctx.fs.dc.models;

  try {
    const createData = ctx.request.body;
    
    // 记录请求数据
    console.log('创建软著请求数据:', JSON.stringify(createData));
    
    // 检查是否存在相同的软件名称和登记号
    const existingRecord = await models.SoftwareCopyright.findOne({
      where: {
        software_name: createData.software_name,
        registration_number: createData.registration_number
      }
    });
    
    if (existingRecord) {
      ctx.status = 400;
      ctx.body = { 
        error: "DuplicateSoftwareCopyright",
        message: "已存在相同软件名称和登记号的软著记录"
      };
      return;
    }
    
    // 确保所有字段都有默认值
    const softwareCopyrightData = {
      software_name: createData.software_name,
      registration_number: createData.registration_number,
      case_number: createData.case_number || null,
      inventors: createData.inventors || null,
      disclosure_time: createData.disclosure_time || null,
      development_complete_date: createData.development_complete_date || null,
      acceptance_date: createData.acceptance_date || null,
      issue_date: createData.issue_date || null,
      related_product: createData.related_product || null,
      related_project: createData.related_project || null,
      type: createData.type || null,
      first_publication_date: createData.first_publication_date || null,
      copyright_holder: createData.copyright_holder || null,
      status: createData.status || null,
      is_core: createData.is_core !== undefined ? createData.is_core : false,
      core_score: createData.core_score || null,
      source_department: createData.source_department || null,
      agent_responsible: createData.agent_responsible || null,
      original_name: createData.original_name || null,
      special_notes: createData.special_notes || null,
      dev_related_project: createData.dev_related_project || null
    };
    
    // 创建新记录
    const newSoftwareCopyright = await models.SoftwareCopyright.create(softwareCopyrightData);
    console.log('创建软著成功:', JSON.stringify(newSoftwareCopyright));
    
    rslt = {
      success: true,
      message: "创建成功",
      data: newSoftwareCopyright
    };
    error = false;  // 设置error为false，表示操作成功
  } catch (e) {
    console.error('创建软著失败:', e);
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "CreateSoftwareCopyrightError" };
  } else {
    ctx.status = 201;
    ctx.body = rslt;
  }
}

/**
 * 编辑软著信息
 */
async function updateSoftwareCopyright(ctx) {
  let error = true;
  let rslt = null;
  let models = ctx.fs.dc.models;

  try {
    const { id } = ctx.params;
    const updateData = ctx.request.body;
    
    // 查找要更新的记录
    const softwareCopyright = await models.SoftwareCopyright.findByPk(id);
    
    if (!softwareCopyright) {
      ctx.status = 404;
      ctx.body = { error: "SoftwareCopyrightNotFound" };
      return;
    }
    
    // 更新数据
    await softwareCopyright.update(updateData);
    
    rslt = {
      success: true,
      message: "更新成功"
    };
    error = false;
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "UpdateSoftwareCopyrightError" };
  } else {
    ctx.status = 200;
    ctx.body = rslt;
  }
}

/**
 * 删除软著
 */
async function deleteSoftwareCopyright(ctx) {
  let error = true;
  let rslt = null;
  let models = ctx.fs.dc.models;

  try {
    const { id } = ctx.params;
    
    // 查找要删除的记录
    const softwareCopyright = await models.SoftwareCopyright.findByPk(id);
    
    if (!softwareCopyright) {
      ctx.status = 404;
      ctx.body = { error: "SoftwareCopyrightNotFound" };
      return;
    }
    
    // 删除记录
    await softwareCopyright.destroy();
    
    rslt = {
      success: true,
      message: "删除成功"
    };
    error = false;
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "DeleteSoftwareCopyrightError" };
  } else {
    ctx.status = 200;
    ctx.body = rslt;
  }
}

/**
 * 导出软著数据
 */
async function exportSoftwareCopyright(ctx) {
  let error = true;
  let models = ctx.fs.dc.models;

  try {
    const { keyword, issueStartDate, issueEndDate } = ctx.request.query;
    
    // 构建查询条件
    const whereCondition = {};
    
    // 关键字搜索
    if (keyword) {
      whereCondition[Op.or] = [
        { software_name: { [Op.like]: `%${keyword}%` } },
        { registration_number: { [Op.like]: `%${keyword}%` } },
        { copyright_holder: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    // 发证时间范围查询
    if (issueStartDate || issueEndDate) {
      whereCondition.issue_date = {};
      
      if (issueStartDate) {
        whereCondition.issue_date[Op.gte] = issueStartDate;
      }
      
      if (issueEndDate) {
        whereCondition.issue_date[Op.lte] = issueEndDate;
      }
    }
    
    // 查询数据
    const list = await models.SoftwareCopyright.findAll({
      where: whereCondition,
      order: [['id', 'DESC']]
    });
    
    // 转换为Excel格式
    const excelData = list.map(item => ({
      '软件名称': item.software_name,
      '我司案号': item.case_number || '',
      '登记号': item.registration_number || '',
      '发明人': item.inventors || '',
      '技术交底书收集时间': item.disclosure_time ? moment(item.disclosure_time).format('YYYY-MM-DD') : '',
      '开发完成日期': item.development_complete_date ? moment(item.development_complete_date).format('YYYY-MM-DD') : '',
      '受理时间': item.acceptance_date ? moment(item.acceptance_date).format('YYYY-MM-DD') : '',
      '发证时间': item.issue_date ? moment(item.issue_date).format('YYYY-MM-DD') : '',
      '关联产品': item.related_product || '',
      '关联立项/课题': item.related_project || '',
      '防御型/攻击型': item.type || '',
      '首次发表日期': item.first_publication_date ? moment(item.first_publication_date).format('YYYY-MM-DD') : '',
      '著作权人': item.copyright_holder || '',
      '状态': item.status || '',
      '是否为核心': item.is_core ? '是' : '否',
      '核心分数': item.core_score || '',
      '来源部门': item.source_department || '',
      '代理负责人': item.agent_responsible || '',
      '原名称': item.original_name || '',
      '特殊事项备注': item.special_notes || '',
      '关联课题/项目': item.dev_related_project || ''
    }));
    
    // 创建工作簿
    const workbook = xlsx.utils.book_new();
    const worksheet = xlsx.utils.json_to_sheet(excelData);
    
    // 添加工作表到工作簿
    xlsx.utils.book_append_sheet(workbook, worksheet, '软著列表');
    
    // 生成随机文件名
    const fileName = `software_copyright_${uuidv4()}.xlsx`;
    const filePath = path.join(__dirname, '../../../../public/temp', fileName);
    
    // 确保目录存在
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    // 写入文件
    xlsx.writeFile(workbook, filePath);
    
    // 设置响应头
    ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    ctx.set('Content-Disposition', `attachment; filename=${encodeURIComponent('软著列表.xlsx')}`);
    
    // 返回文件流
    ctx.body = fs.createReadStream(filePath);
    
    // 设置清理函数，响应结束后删除临时文件
    ctx.res.on('finish', () => {
      fs.unlinkSync(filePath);
    });
    
    error = false;
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
  }

  if (error) {
    ctx.status = 400;
    ctx.body = { error: "ExportSoftwareCopyrightError" };
  }
}

/**
 * 获取软著导入模板
 */
async function getSoftwareCopyrightTemplate(ctx) {
  try {
    // 创建模板数据
    const templateData = [{
      '软件名称': '示例软件名称（必填）',
      '我司案号': 'FS-RZ-2023001',
      '登记号': '2023SR1234567（必填）',
      '发明人': '张三、李四',
      '技术交底书收集时间': '2023-01-01',
      '开发完成日期': '2023-02-01',
      '受理时间': '2023-03-01',
      '发证时间': '2023-04-01',
      '关联产品': '产品A、产品B',
      '关联立项/课题': '项目X',
      '防御型/攻击型': '防御型',
      '首次发表日期': '2023-01-15',
      '著作权人': '飞尚科技有限公司',
      '状态': '原始取得',
      '是否为核心': '是',
      '核心分数': '85',
      '来源部门': '研发部',
      '代理负责人': '王五',
      '原名称': '',
      '特殊事项备注': '',
      '关联课题/项目': '项目Y'
    }];
    
    // 创建工作簿
    const workbook = xlsx.utils.book_new();
    const worksheet = xlsx.utils.json_to_sheet(templateData);
    
    // 添加工作表到工作簿
    xlsx.utils.book_append_sheet(workbook, worksheet, '软著导入模板');
    
    // 生成随机文件名
    const fileName = `software_copyright_template_${uuidv4()}.xlsx`;
    const filePath = path.join(__dirname, '../../../../public/temp', fileName);
    
    // 确保目录存在
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    // 写入文件
    xlsx.writeFile(workbook, filePath);
    
    // 设置响应头
    ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    ctx.set('Content-Disposition', `attachment; filename=${encodeURIComponent('软著导入模板.xlsx')}`);
    
    // 返回文件流
    ctx.body = fs.createReadStream(filePath);
    
    // 设置清理函数，响应结束后删除临时文件
    ctx.res.on('finish', () => {
      fs.unlinkSync(filePath);
    });
  } catch (e) {
    ctx.fs.logger.error(`path: ${ctx.path}, error: ${e}`);
    ctx.status = 400;
    ctx.body = { error: "GetSoftwareCopyrightTemplateError" };
  }
}

module.exports = {
  getSoftwareCopyrightList,
  importSoftwareCopyright,
  createSoftwareCopyright,
  updateSoftwareCopyright,
  deleteSoftwareCopyright,
  exportSoftwareCopyright,
  getSoftwareCopyrightTemplate
}; 